package com.common.util;

import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.support.RequestContext;

public class LocalUtil {
	
	static Logger logger = LoggerFactory.getLogger(LocalUtil.class);
	
	static ResourceBundle localResource = ResourceBundle.getBundle("config", Locale.getDefault());

	public LocalUtil(){};
	/**
	 * 加载指定资源
	 * @param fileName
	 */
	public LocalUtil(String fileName){
		if(StringUtils.isNotBlank(fileName)){
			localResource = ResourceBundle.getBundle(fileName, Locale.getDefault());
		}
	}
	/**
	 * 获取本地messageSource
	 * @param key
	 * @return
	 */
	public static String getMessage(String key){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        RequestContext requestContext = new RequestContext(request);
        String message = requestContext.getMessage(key);
        return StringUtils.defaultString(message);
    }
	/**
	 * 获取指定资源值
	 * @param key
	 * @return
	 */
	public static String getValue(String key){
    	String value = localResource.getString(key);
    	return value;
	}
	/**
	 * 获取系统类型字符串
	 * @return
	 */
	public static String getSysType(){
		Properties prop = System.getProperties();
		return prop.getProperty("os.name");
	}
	/**
	 * 获取web项目根目录
	 * @return
	 */
	public static String getRootPath(){
		String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
		path = path.substring(0, path.indexOf("WEB-INF/"));
		String os = getSysType();
		if(os.startsWith("win") || os.startsWith("Win")){
			path = path.substring(path.indexOf("/") + 1);
		}
		return path;
	}
	/**
	 * 获取web项目下的WEB-INF目录
	 * @return
	 */
	public static String getWebINFPath(){
		String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
		path = path.substring(0, path.indexOf("classes/"));
		String os = getSysType();
		if(os.startsWith("win") || os.startsWith("Win")){
			path = path.substring(path.indexOf("/") + 1);
		}
		return path;
	}

    public static void main(String[] args) {
    	System.out.println("ResourceBundle: " + getValue("domain.name"));
    	System.out.println("ResourceBundle: " + new LocalUtil("log4j").getValue("log4j.rootLogger"));
    	System.out.println("ResourceBundle: " + new LocalUtil("").getValue("domain.name.yeepay"));
    }
	
}
